<?php
/**
 * 命令端: E:\www\yii\webapp\protected>yiic mysql export
 *
 * @author Elwin
 *
 */
class MySqlCommand extends CConsoleCommand
{
	protected $backupBaseDir = '';
	/**
	 *
	 * 登录MySQL用户名
	 *
	 * @var $dbUser
	 */
	protected $dbUser = '';

	/**
	 *
	 * 登录MySQL密码
	 *
	 * @var $dbPwd
	 */
	protected $dbPwd = '';
	/**
	 *
	 * 备份的数据库
	 *
	 * @var array()
	 */
	public $dataBases = array();

	/**
	 *
	 * 备份的数据库文件后缀
	 *
	 * @var string
	 */
	public $extension = '.sql';

	
	public function __construct()
	{
		// echo "<BR>\n__construct()";
	}
	
	/**
	 * 先调用__constrcut,才才会调用init()
	 *
	 */
	public function init()
	{
		$this->dbUser = 'root';
		$this->dbPwd = '123456';
		// echo '<BR>init()';
		$this->dataBases = array('webapp','webshop','webche', 'webcms');
		$this->basePath = Yii::app ()->basePath .DIRECTORY_SEPARATOR;
		$this->backupBaseDir = '..'.DIRECTORY_SEPARATOR. 'database' . DIRECTORY_SEPARATOR.'backup'. DIRECTORY_SEPARATOR;
		// echo "<BR>\ninit()".$this->backupBaseDir;
	}

	public function __set($name , $value)
	{
		$this->$name = $value;
		// echo "\n$name , $value";
	}
	/**
	 * 先调用__constrcut
	 *
	 */

	/**
	 * 在终端执行yiic mysql import,导出MySQL
	 * 
	 * 执行：E:\www\yii\webapp\protected>yiic mysql export
	 */
	public function actionExport()
	{
		// PHP中exec与shell_exec函数区别
		// 是执行Linux命令函数，不同的是获取返回结果不一样，exec只能获取最后一行数据，shell_execu则可以获取全部数据
		foreach($this->dataBases as $database) {
			$dumpConsole = 'mysqldump --database '.$database.' -i > '.$this->backupBaseDir.$database.$this->extension.' -u'.$this->dbUser.' -p'.$this->dbPwd;
			shell_exec ( $dumpConsole );
		}
	}

	/**
	 * 在终端执行yiic mysql import,导入MySQL
	 * 执行：E:\www\yii\webapp\protected>yiic mysql import
	 */
	public function actionImport()
	{
		// 能正确执行
		foreach($this->dataBases as $database) {
			$importConsole = 'mysql -u'.$this->dbUser.' -p'.$this->dbPwd.' < '.$this->backupBaseDir.$database.$this->extension;
			echo shell_exec ( $importConsole);
		}
	}
}
?>